import os
class PeerWebHandler:
    def __init__(self, peer):
        self.peer = peer
    def save_settings(self,**args):        
        for key, val in args.iteritems():
            val = str(val)        
            if key.endswith('port'):
                val = int(val)            
            print "key = ",key,"val=",val,", ",                
            if key.startswith('tracker_'):
                key = key[len('tracker_'):]
                setattr(self.peer.tracker, key, val)
            elif key.startswith('recipe_server_'):
                key = key[len('recipe_server_'):]
                setattr(self.peer.recipe_server, key, val)
            else:
                setattr(self.peer, key, val)
        print
    def share_file(self, fileind, filename):
        fp = open(os.path.join('sample_files', os.listdir('sample_files')[int(fileind)]), 'rb')
        if not filename:
            filename = os.path.basename(fp.name)
        self.peer.save_existing_file(fp, filename)
    def delete_all(self):
        files = os.listdir(self.peer.filedir)
        for f in files:
            print "deleting " ,f 
            os.remove(os.path.join(self.peer.filedir, f))
            
    def refresh_blocks_table(self):
        self.peer.send_blocks = True
    def refresh_recipe_blocks_table(self):
        self.peer.send_recipe_blocks = True
        
    def stop(self):        
        from common import web_server
        self.peer.tracker.remove_peer(self.peer.id)
        web_server.stop()
    
    def pause(self):
        self.peer.pause()
    
    def resume(self):
        self.peer.resume()
    def reset(self):        
        self.peer.reset()
    def search_rs(self, query):
        self.peer.search_rs(query)
    def download_from_rs(self, file_id):
        print "download_from_rs"
        print "file_id = ", file_id        
        self.peer.download_file(file_id)
    def run_sql(self, query):
        self.peer.run_sql(query)
    def web_publish(self):
        peer = self.peer
        m = dict([(x,getattr(peer,x)) for x in ('id',
                                                'name',
                                                'rpc_host',
                                                'rpc_port',
                                                'external_ip',
                                                'external_port',                                                 
                                                'local_recipes', 
                                                'num_unsent_blocks'                                                                                                                                                                                         
                                                 ) ])        
        if peer.rs_search_results is not None:
            m['search_results'] = peer.rs_search_results
            peer.rs_search_results = None                    
        m['recipe_queue'] = [ ( x['id'], 
                                x['name'],
                                x['size'],
                                x['processed']) for x in peer.recipe_queue]  

                
        m['file_queue'] = [(x[0].file_id, 
                            x[0].file_info.name, 
                            x[0].num_blocks - x[0].processed) 
                                for x in peer.file_queue]
        rdq = [(recipe.file_id, 
                recipe.file_info.name,
                recipe.num_blocks, 
                recipe.num_blocks - recipe.blocks_downloaded)
                for recipe in peer.recipe_download_queue]
                                    
        m['recipe_download_queue'] = rdq
        m['tracker_status'] = str(peer.tracker.status)
        m['recipe_server_status'] = str(peer.recipe_server.status)                          
        m.update({'recipe_server_host' : peer.recipe_server.host,
                  'recipe_server_port' : peer.recipe_server.port,
                  'tracker_host' : peer.tracker.host,
                  'tracker_port' : peer.tracker.port,                                                
                  })       
        m.update({'files' : ['%s (%d KB)' % 
                             (x, os.path.getsize('sample_files/%s' % x) / 1024)  
                              for x in os.listdir('sample_files')]})
        if peer.sql_results is not None:
            print "sending sql results"
            m['sql_results'] = peer.sql_results
            peer.sql_results = None               
        return m;
        